package com.zshan.clinic.cms.framework.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;


@Configuration
@EnableTransactionManagement(proxyTargetClass = true) //启注解事务管理，等同于xml配置方式的 <tx:annotation-driven />
@EnableAspectJAutoProxy(exposeProxy = true) //同类中使用切面类调用其他方法
@MapperScan(basePackages = {"com.zshan.clinic.cms.*.mapper"}, sqlSessionFactoryRef = "cmsSqlSessionFactory")
public class CmsDataSourceConfiguration extends AbstractDruidDBConfig {

    @Value("${spring.datasource.cms.url}")
    private String url;

    @Value("${spring.datasource.cms.username}")
    private String username;

    @Value("${spring.datasource.cms.password}")
    private String password;

    @Value("${spring.datasource.cms.mapperLocations}")
    private String [] mapperLocations;

    @Value("${spring.datasource.cms.typeAliasesPackage}")
    private String typeAliasesPackage;

    // 注册 dmpDataSource
    @Bean(name = "cmsDataSource", initMethod = "init", destroyMethod = "close")
    @Primary
    public DruidDataSource dataSource() {
        return super.createDataSource(url, username, password);
    }

    @Bean(name = "cmsSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        return super.sqlSessionFactory(dataSource(),mapperLocations,typeAliasesPackage);
    }

    @Bean(name = "cmsTransactionManager")
    @Primary
    public PlatformTransactionManager cmsTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }
}
